package com.byyy.ccts.core.quartz.utils;

import com.byyy.ccts.core.base.ILogBase;
import com.byyy.ccts.core.message.rocketmq.OAProducer;
import com.byyy.ccts.core.quartz.data.ScheduleJob;
import com.byyy.ccts.core.utils.SpringContextHolder;
import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Method;
import java.text.MessageFormat;

public class TaskUtils implements ILogBase {

	/**
	 * 通过反射调用scheduleJob中定义的方法
	 * 
	 * @param scheduleJob
	 */
	public static void invokMethod(ScheduleJob scheduleJob) {
		Object object = null;
		Class<?> clazz = null;
		if (StringUtils.isNotBlank(scheduleJob.getSpringBean())) {
			object = SpringContextHolder.getBean(scheduleJob.getSpringBean());
		} else if (StringUtils.isNotBlank(scheduleJob.getBeanClass())) {
			try {
				clazz = Class.forName(scheduleJob.getBeanClass());
				object = clazz.newInstance();
			} catch (Exception e) {
				logger.error("实例化出错", e);
			}
		}
		if (object == null) {
			logger.error("任务名称 = [{}]启动成功，请检查是否配置正确！！！", scheduleJob.getJobName());
			return;
		}
		clazz = object.getClass();
		Method method = null;
		try {
			method = clazz.getDeclaredMethod(scheduleJob.getMethodName(), String.class);
		} catch (NoSuchMethodException e) {
			logger.error("任务名称 = [{}]未启动成功，方法名设置错误！！！", scheduleJob.getJobName());
		} catch (SecurityException e) {
			logger.error("任务名称 = [{}]未启动成功，权限错误！！！", scheduleJob.getJobName());
		}
		if (method != null) {
			try {
				method.invoke(object, scheduleJob.getParam());
			} catch (Exception e) {
				OAProducer oAProducer = (OAProducer) SpringContextHolder.getBean("oAProducer");
				oAProducer.sendOAMail("exception", "定时任务执行错误", MessageFormat.format("任务名称 = [{0}]执行错误{1}", scheduleJob.getJobName(), e.getMessage()));
				logger.error(MessageFormat.format("任务名称 = [{0}]执行错误！！！", scheduleJob.getJobName()), e);
			}
		}
	}
}
